<template>
    <div class="mod-config">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList(1)">
            <el-form-item>
                <el-input v-model="dataForm.name" placeholder="试卷名称" clearable @clear="getDataList(1)"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button @click="getDataList(1)">查询</el-button>
                <el-button type="primary" @click="addHandle()">新增</el-button>
            </el-form-item>
        </el-form>
        <el-table
                :data="dataList"
                border
                style="width: 100%;"
                v-loading="dataListLoading">
            <el-table-column
                    prop="ID"
                    type="index"
                    header-align="center"
                    align="center"
                    width="80"
                    label="ID">
            </el-table-column>
            <el-table-column
                    prop="name"
                    header-align="center"
                    align="center"
                    label="名称">
            </el-table-column>
            <el-table-column
                    prop="createTime"
                    header-align="center"
                    align="center"
                    label="时间">
            </el-table-column>
            <el-table-column
                    prop="totalper"
                    header-align="center"
                    align="center"
                    label="分类题库">
            </el-table-column>
            <el-table-column
                    fixed="right"
                    header-align="center"
                    align="center"
                    width="150"
                    label="操作">
                <template slot-scope="scope">
                    <el-button type="text" @click="addHandle(scope.row.id)">修改</el-button>
                    <el-button type="text" @click="deleteHandle(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                @size-change="sizeChangeHandle"
                @current-change="currentChangeHandle"
                :current-page="pageIndex"
                :page-sizes="[10, 20, 50]"
                :page-size="pageSize"
                :total="totalPage"
                layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>

        <!-- 弹窗, 新增 / 修改 -->
        <el-drawer title="配置考试信息" custom-class="drawer-box" :append-to-body="true"
                   :visible="promotionDrawer"
                   size="80%" :close-on-press-escape="false" :show-close="false" :wrapperClosable="false"
                   v-loading="loading">

            <el-row :gutter="20" style="margin: 0">
                <el-col :span="6" :offset="18" class="learn-drawer-range-box-buttons">
                    <el-button class="el-icon-check" type="text" @click="onSubmit"
                               style="color: #67C23A;font-size:24px"/>
                    <el-button class="el-icon-close" type="text" @click="onClose"
                               style="color: #F56C6C;font-size: 24px"/>
                </el-col>
            </el-row>

            <el-form ref="promotionForm" :model="promotionForm" :rules="promotionRule">
                <el-row :gutter="20" style="margin: 0">
                    <el-col :span="24">
                        <el-form-item label="名称" prop="name">
                            <el-input v-model="promotionForm.name" placeholder="考试名称" clearable/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="所属分类" prop="quesCateIds">
                            <div class="ques-cate-id-box">
                                <div>
                                    <el-tag style="margin: 1px 2px" v-for="(item,index) in current" :key="item.id"
                                            closable
                                            @close="currentArrClose(item,index)">
                                        {{item.name}}
                                    </el-tag>
                                </div>
                                <el-button class="ques-cate-id-box-clear" @click="delectCate" type="text">
                                    清除
                                </el-button>
                                <el-button class="ques-cate-id-box-select" @click="checkSort" type="text">
                                    选择分类
                                </el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <exam-type
                        ref="examType"
                        :setUserList="setUserList"
                        :form="promotionForm"
                        :examTypeChange="examTypeChange"
                        :examUserArrClose="examUserArrClose"
                        :setLoading="setLoading"
                        :handleSelectionChange="handleSelectionChange"/>
            </el-form>
        </el-drawer>
        <!-- 分类管理 -->
        <el-dialog title="分类管理" :visible.sync="dialogFormVisible" :show-close="false" append-to-body width="40%">
            <paper-cate ref="paperCate" v-if="paperCate" :showCheckbox="true" :getCheckedNodes="getCheckedNodes"
                        :url="{
                                update:'/exam-admin/ques/cate/update',
                                save:'/exam-admin/ques/cate/save',
                                delete:'/exam-admin/ques/cate/delete',
                                tree:'/exam-admin/ques/cate/tree'
                                }"/>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="getCheckedNodes">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
  import paperCate from './../paper/papercate'
  import ExamType from '../../../components/examType/exam-type'

  export default {
    name: 'professional-promotion',
    data () {
      return {
        loading: false,
        setUserList: [],
        promotionForm: {
          id: '',
          name: '',
          quesCateIds: '',
          userIds: '',
          examType: 0
        },
        promotionDrawer: false,
        dialogFormVisible: false,
        current: [],
        paperCate: false,
        dataForm: {
          name: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        AddExam: false,
        promotionRule: {
          name: [
            {required: true, message: '名称不能为空', trigger: 'blur'}
          ],
          quesCateIds: [
            {required: true, message: '分类id不能为空', trigger: 'blur'}
          ],
          userIds: [
            {required: true, message: '指定人员不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    components: {
      ExamType,
      paperCate
    },
    mounted () {
      this.getDataList()
    },
    methods: {
      onSubmit () {
        if (this.setUserList.length) {
          this.promotionForm.userIds = this.setUserList.map(x => x.userId).join(',')
        }
        this.promotionForm.quesCateIds = this.current.map(x => x.id).join(',')
        this.$refs['promotionForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: this.$http.adornUrl(`/exam-admin/craftbank/${!this.promotionForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.promotionForm
            }).then(data => {
              if (data && data.code === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500
                })
                this.loading = false
                this.onClose()
                this.getDataList()
              } else {
                this.$message.error(data.msg)
              }
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      getCheckedNodes () {
        this.dialogFormVisible = false
        this.current = this.$refs.paperCate.$refs.tree.getCheckedNodes().map(x => ({id: x.id, name: x.name}))
      },
      onClose () {
        this.promotionForm = {
          name: '',
          quesCateIds: '',
          userIds: '',
          examType: 0
        }
        this.setUserList = []
        this.$refs.examType.pagination = {
          page: 1,
          limit: 10
        }
        this.current = []
        this.promotionDrawer = false
      },
      handleSelectionChange (val) {
        if (val.length) {
          this.setUserList = this.setUserList.concat(val)
          this.searchFormInit()
        }
      },
      setLoading (val) {
        this.loading = val
      },
      searchFormInit () {
        this.$refs.examType.$refs.searchForm.search({'userIds': this.setUserList.map(x => x.userId).join(',')})
      },
      initSearchForm (obj) {
        this.$refs.examType.$refs.searchForm.init(obj)
      },
      examTypeChange (val) {
        this.promotionForm.examType = val
        if (val) {
          this.initSearchForm({'userIds': this.setUserList.map(x => x.userId).join(',')})
        }
      },
      currentArrClose (item, index) {
        this.current.splice(index, 1)
      },
      examUserArrClose (item, index) {
        this.setUserList.splice(index, 1)
        this.searchFormInit()
      },
      delectCate () {
        this.current = []
        this.promotionForm.quesCateIds = ''
        this.getDataList()
      },
      checkSort () {
        this.dialogFormVisible = true
        this.paperCate = true
        this.$nextTick(() => {
          this.$refs.paperCate.init(true, this.current.map(x => x.id))
        })
      },
      // 获取数据列表
      getDataList (page) {
        if (page) this.pageIndex = page
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/exam-admin/craftbank/list'),
          method: 'post',
          data: Object.assign({
            'page': this.pageIndex,
            'limit': this.pageSize
          }, this.dataForm)
        }).then(res => {
          if (res && res.code === 200) {
            this.dataList = res.data.list
            this.totalPage = res.data.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 新增 / 修改
      addHandle (id) {
        this.promotionDrawer = true
        if (id) {
          this.dataListLoading = true
          this.$http({
            url: this.$http.adornUrl(`/exam-admin/craftbank/info/${id}`),
            method: 'post'
          }).then(res => {
            if (res && res.code === 200) {
              this.promotionForm = {
                id: id,
                name: res.data.name,
                quesCateIds: res.data.quesCateIds,
                userIds: res.data.userIds,
                examType: res.data.examType
              }
              if (res.data.userInfos && res.data.userInfos.length) {
                this.setUserList = res.data.userInfos.map(x => ({
                  realname: x.realname,
                  gender: x.gender,
                  userId: x.userId
                }))
              }
              if (res.data.quesCateEntities && res.data.quesCateEntities.length) {
                this.current = res.data.quesCateEntities.map(x => ({
                  name: x.name,
                  id: x.id
                }))
              }
              if (this.promotionForm.examType) this.initSearchForm()
            }
            this.dataListLoading = false
          }).catch(_ => {
            this.dataListLoading = false
          })
        }
      },
      // 删除
      deleteHandle (id) {
        this.$confirm(`确定要进行删除操作吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(`/exam-admin/craftbank/delete/${id}`),
            method: 'post'
          }).then(res => {
            if (res && res.code === 200) {
              this.$notify.success({
                title: '提示',
                message: '操作成功'
              })
              this.getDataList()
            } else {
              this.$notify.error({
                title: '提示',
                message: res.msg
              })
            }
          })
        })
      }
    }
  }
</script>
<style lang="scss">
    .ques-cate-id-box {
        display: flex;
        justify-content: flex-end;
        align-items: flex-end;
        clear: both;
        width: 100%;
        min-height: 28px;
        overflow-x: scroll;
        overflow-y: hidden;
        box-sizing: border-box;
        border: 1px solid #DCDFE6;
        border-radius: 4px;

        & > div {
            min-height: 28px;
            flex: 1;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            flex-wrap: wrap;
        }

        .ques-cate-id-box-clear {
            color: #F56C6C;
        }

        .ques-cate-id-box-select {
            color: #409EFF;
        }
    }
</style>
